package com.news.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 新闻前台首页访问量统计
 */
@WebServlet("/hitsCountServlet")
public class HitsCountServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = request.getServletContext();
        // 1.获取页面总访问量
        Integer hitsCount = (Integer) servletContext.getAttribute("hitCounter");
        // 2.判断访问量
        // 2.1如果访问量为null或零，则是首次访问，hitsCount置为1
        // 2.2如果访问量不为null或零，则hitsCount+1后，输出hitsCount
        if (hitsCount == null || hitsCount == 0) {
            hitsCount = 1;
        } else {
            hitsCount += 1;
        }
        // 3.application内置对象中存储键为hitCounter，值为总访问量
        servletContext.setAttribute("hitCounter",hitsCount);
        request.getSession().setAttribute("hitsCount",hitsCount);
    }
}
